package com.stanwind.sgit.exec;

import static com.stanwind.sgit.GitCmdConstant.CMD_GIT_REMOTE;

import com.stanwind.sgit.exception.GitException;
import com.stanwind.sgit.util.StringUtils;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * GitOp
 *
 * @author : Stan
 * @version : 1.0
 * @date :  2019-11-29 14:45
 **/
public class GitRemote extends AbsGitOperation {

    public static final Logger logger = LoggerFactory.getLogger(GitRemote.class);

    public static final String STR_GIT_RES_FAILED = "Could not read from remote repository";
    public static final String STR_GIT_RES_ALREADY_PULL = "Already up to date";
    public static final String PATTERN_PUSH = "(Fetch URL: )(.+)";
    private String remote;

    /**
     * remote origin Fetch URL: F:\gittest\A\Base Push  URL: F:\gittest\A\Base HEAD branch: master Remote branch: master
     * tracked Local branch configured for 'git pull': master merges with remote master Local ref configured for 'git
     * push': master pushes to master (up to date)
     */
    @Override
    protected boolean processExecLog(String msg) throws GitException {
//        logger.debug(msg);
        if (StringUtils.isBlank(msg)) {
            logger.error("get blank msg");
            return false;
        }

        Pattern pattern = Pattern.compile(PATTERN_PUSH);
        Matcher mc = pattern.matcher(msg);
        while (mc.find()) {
            setRemote(mc.group(2));
            logger.debug("git remote url is " +getRemote());
        }

        return true;
    }

    @Override
    public boolean exec(File localRepo) throws GitException {
        return exec(CMD_GIT_REMOTE, localRepo);
    }

    public static void main(String[] args) throws GitException {
        File localRepo = new File("F:\\gittest\\B\\Base");
        GitRemote op = new GitRemote();
        op.exec(localRepo);
    }

    public String getRemote() {
        return remote;
    }

    public void setRemote(String remote) {
        this.remote = remote;
    }
}
